<template>
  <div class="addBrand-container">
    <div class="container">
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="120px">
        <el-form-item label="套餐名称：" prop="name">
          <el-input v-model="formData.name" placeholder="请填写套餐名称" maxlength="14" />
        </el-form-item>
        <el-form-item label="套餐分类：" prop="categoryId">
          <el-select v-model="formData.categoryId" placeholder="请选择套餐分类">
            <el-option v-for="item in categoryList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="套餐价格：" prop="price">
          <el-input v-model="formData.price" placeholder="请设置套餐价格" />
        </el-form-item>

        <el-form-item label="套餐菜品：" required>
          <el-button type="warning" @click="dialogVisible = true">+ 添加菜品</el-button>
          <div v-if="formData.setmealDishes.length" class="dish-table-container">
            <el-table :data="formData.setmealDishes" stripe>
              <el-table-column prop="name" label="名称" />
              <el-table-column prop="price" label="原价">
                <template #default="{ row }">￥{{ row.price.toFixed(2) }}</template>
              </el-table-column>
              <el-table-column label="份数">
                <template #default="{ row }">
                  <el-input-number v-model="row.copies" :min="1" :max="99" size="small" />
                </template>
              </el-table-column>
              <el-table-column label="操作">
                <template #default="{ $index }">
                  <el-button type="text" class="delBut" @click="deleteDishFromSetmeal($index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-form-item>

        <el-form-item label="套餐图片：" prop="image"><!-- 1. action 改为动态绑定 -->
          <!-- 2. 新增 headers 属性，绑定到 uploadHeaders -->
          <el-upload class="avatar-uploader" :action="uploadAction" :headers="uploadHeaders" :show-file-list="false"
            :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
            <img v-if="formData.image" :src="formData.image" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>

        <el-form-item label="套餐描述:">
          <el-input v-model="formData.description" type="textarea" :rows="3" maxlength="200"
            placeholder="套餐描述，最长200字" />
        </el-form-item>

        <div class="subBox">
          <el-form-item>
            <el-button @click="router.back()">取消</el-button>
            <el-button type="primary" @click="submitForm(false)" :loading="isSaving">保存</el-button>
            <el-button v-if="!isEdit" type="warning" @click="submitForm(true)" :loading="isSaving">保存并继续添加</el-button>
          </el-form-item>
        </div>
      </el-form>
    </div>

    <!-- 添加菜品弹窗 -->
    <AddDishDialog v-model:visible="dialogVisible" :initial-selection="formData.setmealDishes"
      @confirm="handleAddDishConfirm" />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import type { FormInstance, FormRules, UploadProps } from 'element-plus';
import { getSetMealById, addSetMeal, editSetMeal } from '@/api/setMeal';
import { getCategoryList } from '@/api/category';
import AddDishDialog from './components/AddDish.vue';
import type { ISetMealAddDTO, ISetMealDish } from '@/types/setMeal';
import type { ICategory } from '@/types/category';
import { useUserStore } from '@/store/user'; // 引入用户信息 store
// --- State ---
const userStore = useUserStore();
const route = useRoute();
const router = useRouter();
const formRef = ref<FormInstance>();
const isSaving = ref(false);
const dialogVisible = ref(false);
const categoryList = ref<ICategory[]>([]);
const formData = reactive<ISetMealAddDTO & { id?: number }>({
  name: '',
  categoryId: '',
  price: '',
  image: '',
  description: '',
  setmealDishes: [],
  status: 1, // 默认为启售
});
// --- 核心修改 1: 保持这个健壮的 isEdit 和 setmealId 判断 ---
const isEdit = computed(() => !!(route.params.id || route.query.id));
const setmealId = computed(() => Number(route.params.id || route.query.id));

// --- 表单校验规则 ---
const formRules = reactive<FormRules>({
  name: [
    {
      required: true,
      validator: (rule: any, value: string, callback: (error?: Error) => void) => {
        if (!value) {
          callback(new Error('请输入套餐名称'));
        } else {
          const reg = /^([A-Za-z0-9\u4e00-\u9fa5]){2,20}$/;
          if (!reg.test(value)) {
            callback(new Error('套餐名称输入不符，请输入2-20个字符'));
          } else {
            callback();
          }
        }
      },
      trigger: 'blur'
    }
  ],
  categoryId: [
    // 旧代码中 prop 名为 idType，在新 formData 中我们统一为 categoryId
    { required: true, message: '请选择套餐分类', trigger: 'change' }
  ],
  price: [
    {
      required: true,
      validator: (rule: any, value: string, callback: (error?: Error) => void) => {
        if (!value) {
          callback(new Error('请输入套餐价格'));
        } else {
          const reg = /^([1-9]\d{0,5}|0)(\.\d{1,2})?$/;
          if (!reg.test(value) || Number(value) <= 0) {
            callback(new Error('价格格式有误，请输入大于零且最多保留两位小数的金额'));
          } else {
            callback();
          }
        }
      },
      trigger: 'blur'
    }
  ],
  image: [
    { required: true, message: '套餐图片不能为空', trigger: 'change' } // trigger: 'change' 在图片上传成功后触发校验
  ]
});

// 3. 定义上传地址
// 我们从环境变量中读取 API 的基础路径，然后拼接上具体的上传路径
// 这样做可以确保在生产环境下地址也是正确的
const uploadAction = computed(() => {
    return `${import.meta.env.VITE_APP_BASE_API}/common/upload`;
});

// 4. 定义包含 token 的请求头
const uploadHeaders = computed(() => {
  return {
    // 这里的 'token' 必须是你后端服务器能识别的那个 key
    // 根据我们之前的调试，它就是 'token'
    'token': userStore.token
  };
});
// --- API Calls & Data Handling ---
const fetchCategoryList = async () => {
  const res = await getCategoryList({ type: 2 });
  categoryList.value = res.data;
};

const fetchSetmealDetail = async (id: number) => {
  try {
    const res = await getSetMealById(id);
    // 使用 Object.assign 将返回的数据合并到 formData 中
    Object.assign(formData, res.data);
  } catch (error) {
    ElMessage.error('获取套餐详情失败');
    router.back(); // 获取失败则返回上一页
  }
};

// --- Event Handlers ---
const handleAvatarSuccess: UploadProps['onSuccess'] = (response) => {
  if (response.code === 1) {
    formData.image = response.data;
    ElMessage.success('图片上传成功！');
  } else {
    ElMessage.error(response.msg || '图片上传失败');
  }
};

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (!['image/jpeg', 'image/png'].includes(rawFile.type)) {
    ElMessage.error('图片必须是 JPG 或 PNG 格式!');
    return false;
  }
  if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片大小不能超过 2MB!');
    return false;
  }
  return true;
};

const handleAddDishConfirm = (selectedDishes: ISetMealDish[]) => {
  formData.setmealDishes = selectedDishes;
  dialogVisible.value = false;
};

const deleteDishFromSetmeal = (index: number) => {
  formData.setmealDishes.splice(index, 1);
};

// --- 优化 submitForm ---
const submitForm = async (continueAdding: boolean) => {
  if (!formRef.value) return;
  await formRef.value.validate(async (valid) => {
    if (valid) {
      if (formData.setmealDishes.length === 0) return ElMessage.error('套餐菜品不能为空');

      isSaving.value = true;
      try {
        // 准备提交的数据
        const dataToSubmit = { ...formData };

        if (isEdit.value) {
          // 如果是编辑模式，确保提交的数据里有 id
          dataToSubmit.id = setmealId.value;
          await editSetMeal(dataToSubmit as any);
          ElMessage.success('套餐修改成功！');
          router.push('/setmeal');
        } else {
          // 新增模式
          await addSetMeal(dataToSubmit);
          ElMessage.success('套餐添加成功！');
          if (continueAdding) {
            formRef.value?.resetFields();
            formData.setmealDishes = [];
            formData.image = ''; // 清空图片
          } else {
            router.push('/setmeal');
          }
        }
      } finally {
        isSaving.value = false;
      }
    }
  });
};
// --- Lifecycle Hook ---
onMounted(() => {
  fetchCategoryList();
  if (isEdit.value) {
    // fetchSetmealDetail(Number(route.query.id));
     fetchSetmealDetail(setmealId.value);
  }
});
</script>

<style lang="scss" scoped>
.addBrand-container {
  padding: 20px;
}

.container {
  background-color: #fff;
  padding: 30px;
  border-radius: 4px;
}

.el-input {
  width: 350px;
}

.dish-table-container {
  width: 100%;
  margin-top: 10px;
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
